package aftersale

import (
	"context"
	// "fmt"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/order/rpc/internal/svc"
	"mall/service/order/rpc/internal/utils/errorhandler"
	"mall/service/order/rpc/types/order"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateAfterSaleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateAfterSaleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateAfterSaleLogic {
	return &BackendUpdateAfterSaleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendUpdateAfterSaleLogic) BackendUpdateAfterSale(in *order.AfterSaleInfo) (*order.BaseResp, error) {
	// logrus.Info(fmt.Sprintf("AfterSaleInfo: %+v", in))
	if in.Id == nil || *in.Id == 0 || in.AfterSaleType == nil || *in.AfterSaleType == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	//查询后修改
	result, err := l.svcCtx.AfterSaleRequest.FindOneNoCache(l.ctx, nil, *in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if uint32(result.AfterSaleType) != *in.AfterSaleType {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.Status != nil {
		result.Status = uint8(*in.Status)
	}
	if in.ReasonForRefusal != nil {
		result.ReasonForRefusal = *in.ReasonForRefusal
	}
	err = l.svcCtx.AfterSaleRequest.Update(l.ctx, nil, result)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &order.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
